<?php

namespace App\Models\Goods;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;

/**
 * 商品模型类
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Models
 */
class Products extends BaseModel
{

    protected $table = 'b2c_goods_product';
    protected $primaryKey = 'product_id';
    protected $casts = [
        'spec_ids' => 'array'
    ];

    /**
     * 根据ID获取商品
     *
     * @param int $productId
     * @param bool $lock
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getById(int $productId, bool $lock = false)
    {
        $query = Products::query()->where('product_id', $productId);
        if($lock) {
            $query->lockForUpdate();
        }
        return $query->first();
    }

    /**
     * 获取商品总库存
     *
     * @param int $goodsId
     * @return int
     */
    public static function getStock(int $goodsId)
    {
        return (int)Products::query()->where('goods_id', $goodsId)->sum('stock_qty');
    }

    /**
     * 根据主商品ID获取商品
     *
     * @param int $goodsId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getByGoodsId(int $goodsId)
    {
        return Products::query()->where('goods_id', $goodsId)->get();
    }

    /**
     * 保存商品信息
     *
     * @param array $data
     * @return int|mixed
     */
    public static function saveData(array $data)
    {
        $product = empty($data['product_id']) ? new Products() : Products::find($data['product_id']);
        $product->goods_id = $data['goods_id'];
        $product->stock_qty = $data['stock_qty'];
        $product->sales_price = $data['sales_price'];
        $product->market_price = $data['market_price'];
        $product->specs = $data['specs'];
        $product->image_url = $data['image_url'];
        $product->on_sale = $data['on_sale'];
        $product->spec_ids = $data['spec_ids'];
        $product->spec_ids_str = implode('_', $data['spec_ids']);
        return $product->save() ? $product->product_id : 0;
    }
}
